<template>
  <div class="balance-bg">
    <el-card class="balance-card">
      <div class="balance-header">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <div class="balance-title">账户余额</div>
        <el-button @click="refreshBalance" icon="Refresh" :loading="loading">刷新</el-button>
      </div>

      <div v-if="loading" class="loading-container">
        <el-loading-spinner />
        <p>加载中...</p>
      </div>

      <div v-else class="balance-content">
        <!-- 余额卡片 -->
        <div class="balance-cards">
          <el-card class="balance-item total-balance">
            <div class="balance-info">
              <div class="balance-label">总余额</div>
              <div class="balance-amount">¥{{ formatAmount(balanceInfo.balance) }}</div>
            </div>
            <div class="balance-icon">
              <el-icon><Wallet /></el-icon>
            </div>
          </el-card>

          <el-card class="balance-item available-balance">
            <div class="balance-info">
              <div class="balance-label">可用余额</div>
              <div class="balance-amount">¥{{ formatAmount(balanceInfo.available_balance) }}</div>
            </div>
            <div class="balance-icon">
              <el-icon><Money /></el-icon>
            </div>
          </el-card>

          <el-card class="balance-item frozen-balance">
            <div class="balance-info">
              <div class="balance-label">冻结金额</div>
              <div class="balance-amount">¥{{ formatAmount(balanceInfo.frozen_amount) }}</div>
            </div>
            <div class="balance-icon">
              <el-icon><Lock /></el-icon>
            </div>
          </el-card>
        </div>

        <!-- 操作按钮 -->
        <div class="balance-actions">
          <el-button type="primary" size="large" @click="showRechargeDialog">
            <el-icon><Plus /></el-icon>
            充值
          </el-button>
          <el-button size="large" @click="showTransactionHistory">
            <el-icon><List /></el-icon>
            交易记录
          </el-button>
          <el-button type="success" size="large" @click="showIncomeAnalysis">
            <el-icon><TrendCharts /></el-icon>
            收入分析
          </el-button>
        </div>

        <!-- 账户状态 -->
        <div class="account-status">
          <el-tag :type="getStatusType(balanceInfo.status)">
            {{ getStatusText(balanceInfo.status) }}
          </el-tag>
          <span class="update-time">
            更新时间：{{ formatTime(balanceInfo.updated_at) }}
          </span>
        </div>
      </div>

      <!-- 充值对话框 -->
      <el-dialog v-model="rechargeDialogVisible" title="账户充值" width="400px">
        <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="80px">
          <el-form-item label="充值金额" prop="amount">
            <el-input-number 
              v-model="rechargeForm.amount" 
              :precision="2" 
              :min="0.01" 
              :max="10000"
              placeholder="请输入充值金额"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="rechargeForm.remark" 
              placeholder="请输入备注信息（可选）"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRecharge" :loading="rechargeLoading">
            {{ rechargeLoading ? '充值中...' : '确认充值' }}
          </el-button>
        </template>
      </el-dialog>

      <!-- 交易记录对话框 -->
      <el-dialog v-model="transactionDialogVisible" title="交易记录" width="800px">
        <div class="transaction-filters">
          <el-form :model="transactionQuery" inline>
            <el-form-item label="查询类型">
              <el-select v-model="transactionQuery.date_type" @change="fetchTransactionHistory">
                <el-option label="全部" value="all" />
                <el-option label="按日查询" value="daily" />
                <el-option label="按月查询" value="monthly" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期" v-if="transactionQuery.date_type !== 'all'">
              <el-date-picker
                v-model="transactionQuery.start_date"
                :type="transactionQuery.date_type === 'daily' ? 'date' : 'month'"
                placeholder="选择开始日期"
                @change="fetchTransactionHistory"
              />
            </el-form-item>
            <el-form-item label="结束日期" v-if="transactionQuery.date_type !== 'all'">
              <el-date-picker
                v-model="transactionQuery.end_date"
                :type="transactionQuery.date_type === 'daily' ? 'date' : 'month'"
                placeholder="选择结束日期"
                @change="fetchTransactionHistory"
              />
            </el-form-item>
          </el-form>
        </div>

        <el-table :data="transactionList" style="width: 100%" v-loading="transactionLoading">
          <el-table-column prop="transaction_type" label="交易类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.transaction_type === 0 ? 'success' : 'danger'">
                {{ scope.row.transaction_type === 0 ? '收入' : '支出' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="金额" width="120">
            <template #default="scope">
              <span :class="scope.row.transaction_type === 0 ? 'income-amount' : 'expense-amount'">
                {{ scope.row.transaction_type === 0 ? '+' : '-' }}¥{{ formatAmount(scope.row.amount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="balance" label="余额" width="120">
            <template #default="scope">
              ¥{{ formatAmount(scope.row.balance) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip />
          <el-table-column prop="transaction_time" label="交易时间" width="180">
            <template #default="scope">
              {{ formatTime(scope.row.transaction_time) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="transaction-pagination">
          <el-pagination
            v-model:current-page="transactionQuery.page"
            :page-size="transactionQuery.page_size"
            :total="transactionTotal"
            layout="total, prev, pager, next"
            @current-change="fetchTransactionHistory"
          />
        </div>
      </el-dialog>

      <!-- 收入分析对话框 -->
      <el-dialog v-model="incomeAnalysisDialogVisible" title="收入分析" width="900px">
        <div class="income-analysis-filters">
          <el-form :model="incomeAnalysisQuery" inline>
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="incomeAnalysisQuery.start_date"
                type="date"
                placeholder="选择开始日期"
                @change="fetchIncomeAnalysis"
              />
            </el-form-item>
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="incomeAnalysisQuery.end_date"
                type="date"
                placeholder="选择结束日期"
                @change="fetchIncomeAnalysis"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchIncomeAnalysis" :loading="incomeAnalysisLoading">
                分析收入
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <div v-if="incomeAnalysisData" class="income-analysis-content">
          <!-- 收入概览 -->
          <el-card class="income-overview" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>收入概览</span>
              </div>
            </template>
            <div class="income-stats">
              <div class="stat-item">
                <div class="stat-label">总收入</div>
                <div class="stat-value income">¥{{ formatAmount(incomeAnalysisData.total_income) }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">订单数量</div>
                <div class="stat-value">{{ incomeAnalysisData.order_count }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">平均单价</div>
                <div class="stat-value">¥{{ formatAmount(incomeAnalysisData.avg_order_amount) }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">活跃天数</div>
                <div class="stat-value">{{ incomeAnalysisData.active_days }}</div>
              </div>
            </div>
          </el-card>

          <!-- 收入趋势 -->
          <el-card class="income-trend" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>收入趋势</span>
              </div>
            </template>
            <div class="trend-chart" ref="trendChartRef"></div>
          </el-card>

          <!-- 分析总结 -->
          <el-card class="income-summary" shadow="hover" v-if="incomeAnalysisData.analysis_summary">
            <template #header>
              <div class="card-header">
                <span>分析总结</span>
              </div>
            </template>
            <div class="summary-content">
              <p>{{ incomeAnalysisData.analysis_summary }}</p>
            </div>
          </el-card>

          <!-- 优化建议 -->
          <el-card class="income-suggestions" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>优化建议</span>
              </div>
            </template>
            <div class="suggestions-list">
              <div v-if="incomeAnalysisData.suggestions && incomeAnalysisData.suggestions.length > 0">
                <div v-for="(suggestion, index) in incomeAnalysisData.suggestions" :key="index" class="suggestion-item">
                  <el-icon class="suggestion-icon"><TrendCharts /></el-icon>
                  <div class="suggestion-content">
                    <div class="suggestion-title">{{ suggestion.title }}</div>
                    <div class="suggestion-desc">{{ suggestion.description }}</div>
                  </div>
                </div>
              </div>
              <div v-else class="no-suggestions">
                <el-empty description="暂无优化建议" :image-size="60" />
              </div>
            </div>
          </el-card>

          <!-- 操作按钮 -->
          <div class="income-actions">
            <el-button 
              type="primary" 
              @click="pushIncomeReport" 
              :loading="pushReportLoading"
              :disabled="pushReportLoading || exportReportLoading"
            >
              <el-icon><Upload /></el-icon>
              {{ pushReportLoading ? '推送中...' : '推送报告' }}
            </el-button>
            <el-button 
              @click="exportIncomeReport"
              :loading="exportReportLoading"
              :disabled="pushReportLoading || exportReportLoading"
            >
              <el-icon><Download /></el-icon>
              {{ exportReportLoading ? '导出中...' : '导出报告' }}
            </el-button>
          </div>
        </div>

        <div v-else-if="!incomeAnalysisLoading" class="no-data">
          <el-empty description="请选择日期范围并点击分析按钮" />
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Wallet, Money, Lock, Plus, List, TrendCharts, Upload, Download } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { financeAPI } from '@/api/finance'

const router = useRouter()
const loading = ref(false)
const rechargeDialogVisible = ref(false)
const transactionDialogVisible = ref(false)
const rechargeLoading = ref(false)
const transactionLoading = ref(false)
const rechargeFormRef = ref()

// 余额信息
const balanceInfo = ref({
  balance: 0,
  frozen_amount: 0,
  available_balance: 0,
  status: 'active',
  updated_at: null
})

// 充值表单
const rechargeForm = ref({
  amount: null,
  remark: ''
})

// 充值表单验证规则
const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 10000, message: '充值金额必须在0.01-10000之间', trigger: 'blur' }
  ]
}

// 交易记录查询参数
const transactionQuery = ref({
  date_type: 'all',
  start_date: null,
  end_date: null,
  page: 1,
  page_size: 20
})

const transactionList = ref([])
const transactionTotal = ref(0)

// 收入分析相关
const incomeAnalysisDialogVisible = ref(false)
const incomeAnalysisLoading = ref(false)
const incomeAnalysisData = ref(null)
const trendChartRef = ref()

// 报告操作加载状态
const pushReportLoading = ref(false)
const exportReportLoading = ref(false)

// 收入分析查询参数
const incomeAnalysisQuery = ref({
  start_date: null,
  end_date: null
})

onMounted(() => {
  fetchBalance()
})

// 监听收入分析对话框关闭，重置加载状态
watch(incomeAnalysisDialogVisible, (newVal) => {
  if (!newVal) {
    // 对话框关闭时重置加载状态
    pushReportLoading.value = false
    exportReportLoading.value = false
  }
})

// 获取余额信息
async function fetchBalance() {
  try {
    loading.value = true
    const userId = localStorage.getItem('userid')

    console.log('获取用户ID:', userId)
    console.log('localStorage内容:', localStorage)

    if (!userId) {
      ElMessage.error('用户未登录，请先登录')
      router.push('/login')
      return
    }

    const response = await financeAPI.getDriverBalance(userId)

    // 适配原始响应格式，直接使用response.data
    if (response.data) {
      balanceInfo.value = response.data
    }
  } catch (error) {
    console.error('获取余额失败:', error)
    console.error('错误详情:', error.response)
    if (error.response && error.response.data && error.response.data.error) {
      ElMessage.error(`获取余额失败: ${error.response.data.error}`)
    } else if (error.response && error.response.status) {
      ElMessage.error(`获取余额失败: HTTP ${error.response.status}`)
    } else {
      ElMessage.error('获取余额信息失败，请检查网络连接')
    }
  } finally {
    loading.value = false
  }
}

// 刷新余额
function refreshBalance() {
  fetchBalance()
}

// 显示充值对话框
function showRechargeDialog() {
  rechargeForm.value = {
    amount: null,
    remark: ''
  }
  rechargeDialogVisible.value = true
}

// 提交充值
async function submitRecharge() {
  if (!rechargeFormRef.value) return

  try {
    await rechargeFormRef.value.validate()
    rechargeLoading.value = true

    const userId = localStorage.getItem('userid')
    console.log('充值 - 获取用户ID:', userId)

    if (!userId) {
      ElMessage.error('用户未登录，请先登录')
      return
    }

    const data = {
      driver_id: userId,
      amount: rechargeForm.value.amount,
      remark: rechargeForm.value.remark || '账户充值'
    }

    const response = await financeAPI.increaseBalance(data)
    // 适配原始响应格式
    if (response.data && response.data.message) {
      ElMessage.success(response.data.message)
    } else {
      ElMessage.success('充值成功')
    }
    rechargeDialogVisible.value = false
    fetchBalance() // 刷新余额
  } catch (error) {
    console.error('充值失败:', error)
    if (error.response && error.response.data && error.response.data.error) {
      ElMessage.error(error.response.data.error)
    } else {
      ElMessage.error('充值失败，请重试')
    }
  } finally {
    rechargeLoading.value = false
  }
}

// 显示交易记录
function showTransactionHistory() {
  transactionDialogVisible.value = true
  fetchTransactionHistory()
}

// 获取交易记录
async function fetchTransactionHistory() {
  try {
    transactionLoading.value = true
    const userId = localStorage.getItem('userid')
    console.log('交易记录 - 获取用户ID:', userId)

    if (!userId) {
      ElMessage.error('用户未登录，请先登录')
      return
    }

    const params = {
      driver_id: userId,
      date_type: transactionQuery.value.date_type,
      page: transactionQuery.value.page,
      page_size: transactionQuery.value.page_size
    }

    if (transactionQuery.value.start_date) {
      params.start_date = formatDate(transactionQuery.value.start_date, transactionQuery.value.date_type)
    }
    if (transactionQuery.value.end_date) {
      params.end_date = formatDate(transactionQuery.value.end_date, transactionQuery.value.date_type)
    }

    const response = await financeAPI.getTransactionHistory(params)

    // 适配原始响应格式
    if (response.data) {
      transactionList.value = response.data.transactions || []
      transactionTotal.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取交易记录失败:', error)
    if (error.response && error.response.data && error.response.data.error) {
      ElMessage.error(error.response.data.error)
    } else {
      ElMessage.error('获取交易记录失败')
    }
  } finally {
    transactionLoading.value = false
  }
}

// 格式化金额
function formatAmount(amount) {
  return Number(amount || 0).toFixed(2)
}

// 格式化时间
function formatTime(time) {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

// 格式化日期
function formatDate(date, type) {
  if (!date) return ''
  const d = new Date(date)
  if (type === 'daily') {
    return d.toISOString().split('T')[0] // YYYY-MM-DD
  } else if (type === 'monthly') {
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}` // YYYY-MM
  }
  return ''
}

// 获取状态类型
function getStatusType(status) {
  const map = {
    'active': 'success',
    'frozen': 'warning',
    'disabled': 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
function getStatusText(status) {
  const map = {
    'active': '正常',
    'frozen': '冻结',
    'disabled': '禁用'
  }
  return map[status] || '未知'
}

// 返回上一页
function goBack() {
  router.back()
}

// 显示收入分析对话框
function showIncomeAnalysis() {
  incomeAnalysisDialogVisible.value = true
  // 设置默认日期范围为最近30天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(endDate.getDate() - 30)
  
  incomeAnalysisQuery.value.start_date = startDate
  incomeAnalysisQuery.value.end_date = endDate
  
  // 重置加载状态
  pushReportLoading.value = false
  exportReportLoading.value = false
}

// 获取收入分析数据
async function fetchIncomeAnalysis() {
  try {
    if (!incomeAnalysisQuery.value.start_date || !incomeAnalysisQuery.value.end_date) {
      ElMessage.warning('请选择开始和结束日期')
      return
    }

    incomeAnalysisLoading.value = true
    const userId = localStorage.getItem('userid')
    
    if (!userId) {
      ElMessage.error('用户未登录，请先登录')
      return
    }

    const params = {
      driver_id: userId,
      start_date: formatDate(incomeAnalysisQuery.value.start_date, 'daily'),
      end_date: formatDate(incomeAnalysisQuery.value.end_date, 'daily')
    }

    const response = await financeAPI.getDriverIncomeAnalysis(params)
    
    if (response.data && response.data.code === 200) {
      // 转换后端数据格式为前端期望的格式
      const backendData = response.data.data
      incomeAnalysisData.value = {
        total_income: backendData.summary?.total_income || 0,
        order_count: backendData.summary?.total_orders || 0,
        avg_order_amount: backendData.summary?.avg_order_amount || 0,
        active_days: backendData.active_days || 0,
        trend_data: backendData.trend_data || [],
        suggestions: formatSuggestions(backendData.analysis?.recommendations || []),
        analysis_summary: backendData.analysis?.analysis_summary || '',
        driver_info: backendData.driver_info || {},
        period: backendData.period || {}
      }
      
      console.log('转换后的数据:', incomeAnalysisData.value)
      
      // 渲染趋势图表
      nextTick(() => {
        renderTrendChart()
      })
    } else {
      ElMessage.error(response.data?.message || '获取收入分析数据失败')
    }
  } catch (error) {
    console.error('获取收入分析数据失败:', error)
    ElMessage.error('获取收入分析数据失败: ' + error.message)
  } finally {
    incomeAnalysisLoading.value = false
  }
}

// 渲染趋势图表
function renderTrendChart() {
  console.log('开始渲染趋势图表')
  console.log('incomeAnalysisData:', incomeAnalysisData.value)
  console.log('trendChartRef:', trendChartRef.value)
  
  if (!incomeAnalysisData.value?.trend_data || !trendChartRef.value) {
    console.log('缺少必要数据，无法渲染趋势图表')
    return
  }

  const chartContainer = trendChartRef.value
  const trendData = incomeAnalysisData.value.trend_data
  
  console.log('趋势数据:', trendData)
  
  // 清空容器
  chartContainer.innerHTML = ''
  
  // 创建ECharts实例
  const chart = echarts.init(chartContainer)
  
  // 准备数据
  const dates = trendData.map(item => item.date)
  const incomes = trendData.map(item => item.income)
  const orders = trendData.map(item => item.orders)
  
  // 配置图表选项
  const option = {
    title: {
      text: '收入趋势',
      left: 'center',
      textStyle: {
        color: '#333',
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>'
        params.forEach(param => {
          if (param.seriesName === '收入') {
            result += `${param.seriesName}: ¥${formatAmount(param.value)}<br/>`
          } else {
            result += `${param.seriesName}: ${param.value}<br/>`
          }
        })
        return result
      }
    },
    legend: {
      data: ['收入', '订单数'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '收入 (¥)',
        position: 'left',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '收入',
        type: 'line',
        data: incomes,
        smooth: true,
        lineStyle: {
          color: '#67C23A',
          width: 3
        },
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
            ]
          }
        }
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        data: orders,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  // 渲染图表
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
  
  console.log('ECharts趋势图表渲染完成')
}

// 推送收入报告
async function pushIncomeReport() {
  try {
    if (!incomeAnalysisData.value) {
      ElMessage.warning('请先进行收入分析')
      return
    }

    const userId = localStorage.getItem('userid')
    if (!userId) {
      ElMessage.error('用户未登录，请先登录')
      return
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要推送收入报告吗？报告将发送到相关系统。',
      '确认推送',
      {
        confirmButtonText: '确定推送',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    pushReportLoading.value = true

    const data = {
      driver_id: userId,
      analysis_result: {
        summary: {
          total_income: incomeAnalysisData.value.total_income,
          total_orders: incomeAnalysisData.value.order_count,
          avg_order_amount: incomeAnalysisData.value.avg_order_amount,
          growth_rate: 0
        },
        trend_data: incomeAnalysisData.value.trend_data,
        suggestions: incomeAnalysisData.value.suggestions,
        analysis_summary: incomeAnalysisData.value.analysis_summary,
        driver_info: incomeAnalysisData.value.driver_info,
        period: incomeAnalysisData.value.period,
        active_days: incomeAnalysisData.value.active_days
      },
      report_date: formatDate(new Date(), 'daily'),
      report_type: 'income_analysis'
    }

    console.log('推送报告数据:', data)
    const response = await financeAPI.pushIncomeReport(data)
    console.log('推送报告响应:', response)
    
    if (response.data && response.data.code === 200) {
      ElMessage({
        message: '收入报告推送成功',
        type: 'success',
        duration: 3000,
        showClose: true
      })
    } else {
      console.error('推送失败响应:', response)
      ElMessage.error(response.data?.message || '推送失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      return // 用户取消操作
    }
    console.error('推送收入报告失败:', error)
    console.error('错误详情:', error.response)
    
    let errorMessage = '推送收入报告失败，请重试'
    if (error.response && error.response.data) {
      if (error.response.data.error) {
        errorMessage = `推送失败: ${error.response.data.error}`
      } else if (error.response.data.message) {
        errorMessage = `推送失败: ${error.response.data.message}`
      } else if (error.response.status) {
        errorMessage = `推送失败: HTTP ${error.response.status}`
      }
    }
    
    ElMessage.error(errorMessage)
  } finally {
    pushReportLoading.value = false
  }
}

// 导出收入报告
async function exportIncomeReport() {
  try {
    if (!incomeAnalysisData.value) {
      ElMessage.warning('请先进行收入分析')
      return
    }

    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要导出收入报告吗？',
      '确认导出',
      {
        confirmButtonText: '确定导出',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    exportReportLoading.value = true

    // 创建CSV内容
    const csvContent = generateCSVContent(incomeAnalysisData.value)
    
    // 生成文件名
    const fileName = `收入分析报告_${formatDate(new Date(), 'daily')}_${new Date().getTime()}.csv`
    
    // 下载文件
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', fileName)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage({
      message: '收入报告导出成功',
      type: 'success',
      duration: 3000,
      showClose: true
    })
  } catch (error) {
    if (error === 'cancel') {
      return // 用户取消操作
    }
    console.error('导出收入报告失败:', error)
    ElMessage.error('导出收入报告失败，请重试')
  } finally {
    exportReportLoading.value = false
  }
}

// 格式化建议数据
function formatSuggestions(recommendations) {
  if (!Array.isArray(recommendations)) {
    return []
  }
  
  return recommendations.map((recommendation, index) => ({
    title: `优化建议 ${index + 1}`,
    description: recommendation,
    priority: '一般'
  }))
}

// 生成CSV内容
function generateCSVContent(data) {
  const reportDate = formatDate(new Date(), 'daily')
  const reportTime = new Date().toLocaleString('zh-CN')
  
  // 报告头部信息
  const headerRows = [
    ['收入分析报告'],
    ['生成时间', reportTime],
    ['报告日期', reportDate],
    ['', ''], // 空行
  ]
  
  // 收入概览
  const overviewRows = [
    ['收入概览'],
    ['指标', '数值', '单位', '备注'],
    ['总收入', formatAmount(data.total_income), '元', '分析期间内总收入'],
    ['订单数量', data.order_count, '单', '分析期间内订单总数'],
    ['平均单价', formatAmount(data.avg_order_amount), '元', '平均每单收入'],
    ['活跃天数', data.active_days, '天', '有收入的活跃天数'],
    ['', '', '', ''], // 空行
  ]
  
  // 趋势数据
  let trendRows = []
  if (data.trend_data && data.trend_data.length > 0) {
    trendRows = [
      ['收入趋势'],
      ['日期', '收入(元)', '订单数', '日均收入'],
      ...data.trend_data.map(item => [
        item.date, 
        formatAmount(item.income), 
        item.orders || 0,
        formatAmount((item.income / (item.orders || 1)).toFixed(2))
      ]),
      ['', '', '', ''], // 空行
    ]
  }
  
  // 优化建议
  let suggestionRows = []
  if (data.suggestions && data.suggestions.length > 0) {
    suggestionRows = [
      ['优化建议'],
      ['序号', '建议标题', '建议描述', '优先级'],
      ...data.suggestions.map((suggestion, index) => [
        index + 1,
        suggestion.title,
        suggestion.description,
        suggestion.priority || '一般'
      ]),
      ['', '', '', ''], // 空行
    ]
  }
  
  // 报告总结
  const summaryRows = [
    ['报告总结'],
    ['分析结论', '根据收入数据分析，建议重点关注收入增长和订单质量提升'],
    ['生成时间', reportTime],
    ['报告状态', '已完成'],
  ]
  
  // 合并所有行
  const allRows = [
    ...headerRows,
    ...overviewRows,
    ...trendRows,
    ...suggestionRows,
    ...summaryRows
  ]
  
  // 转换为CSV格式，处理包含逗号的内容
  return allRows.map(row => 
    row.map(cell => {
      if (cell && cell.toString().includes(',')) {
        return `"${cell}"`
      }
      return cell || ''
    }).join(',')
  ).join('\n')
}
</script>

<style scoped>
.balance-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.balance-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.balance-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.balance-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.loading-container {
  padding: 60px 20px;
  text-align: center;
  color: #666;
}

.balance-content {
  padding: 24px;
}

.balance-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.balance-item {
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.balance-item:hover {
  transform: translateY(-4px);
}

.total-balance {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.available-balance {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.frozen-balance {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.balance-item :deep(.el-card__body) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px;
  background: transparent;
}

.balance-info {
  flex: 1;
}

.balance-label {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 8px;
}

.balance-amount {
  font-size: 28px;
  font-weight: bold;
}

.balance-icon {
  font-size: 48px;
  opacity: 0.6;
}

.balance-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-bottom: 24px;
}

.account-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.update-time {
  color: #666;
  font-size: 14px;
}

.transaction-filters {
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.transaction-pagination {
  margin-top: 16px;
  text-align: center;
}

.income-amount {
  color: #67c23a;
  font-weight: bold;
}

.expense-amount {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

/* 收入分析样式 */
.income-analysis-filters {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.income-analysis-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.income-overview {
  border-radius: 12px;
}

.income-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.stat-value.income {
  color: #67c23a;
}

.income-trend {
  border-radius: 12px;
}

.trend-chart {
  height: 400px;
  padding: 20px;
  width: 100%;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.trend-data {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.trend-item {
  flex: 1;
  min-width: 120px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  text-align: center;
}

.trend-date {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.trend-income {
  font-size: 16px;
  font-weight: 600;
  color: #67c23a;
}

.income-suggestions {
  border-radius: 12px;
}

.income-summary {
  border-radius: 12px;
}

.summary-content {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  line-height: 1.6;
  color: #333;
}

.summary-content p {
  margin: 0;
  font-size: 14px;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.suggestion-icon {
  color: #409eff;
  font-size: 20px;
  margin-top: 2px;
}

.suggestion-content {
  flex: 1;
}

.suggestion-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.suggestion-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.no-suggestions {
  padding: 40px 20px;
  text-align: center;
}

.income-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e9ecef;
}

.income-actions .el-button {
  min-width: 120px;
  height: 40px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.income-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.no-data {
  padding: 60px 20px;
  text-align: center;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
</style>
